//
//  ApplyStateViewController.swift
//  LongTermInsurance
//
//  Created by zolobdz on 2018/11/28.
//  Copyright © 2018年 HeChao. All rights reserved.
//

import UIKit
import ObjectMapper
import RxSwift
import RxCocoa

class ApplyStateViewController: UIViewController {

    lazy var saveButton: UIButton = {
        let button = UIButton()
        button.setTitle("保  存", for: .normal)
        button.backgroundColor = CDColor.themePink
        return button
    }()
    
    lazy var questionView: QuestionView = {
        let view = QuestionView()
        return view
    }()
    
    lazy var dataSource: [QuestionModel] = {
        
        let path = CDArchiverPath.liveStateFilePath
        if FileManager.default.fileExists(atPath: path) {
            if let dict = NSDictionary(contentsOfFile: path) {
                if let array = dict["live"] as? [[String: Any]]{
                    let array = Mapper<QuestionModel>().mapArray(JSONArray: array)
                    return array
                }
            }
        }
        
        let plistPath = Bundle.main.url(forResource: "apply_live", withExtension: "plist")!
        let dataDict = NSArray(contentsOf: plistPath) as! [[String: Any]]
        let array = Mapper<QuestionModel>().mapArray(JSONArray: dataDict)
        return array
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "目前生活状况"
        view.backgroundColor = CDColor.grayBackgroundColorA
        view.addSubview(questionView)
        view.addSubview(saveButton)
        
        questionView.snp.remakeConstraints { (make) in
            make.top.right.left.equalTo(0)
            make.bottom.equalTo(saveButton.snp.top).offset(-20)
        }
        
        saveButton.snp.remakeConstraints { (make) in
            make.left.equalTo(20)
            make.right.equalTo(-20)
            if #available(iOS 11.0, *) {
                make.bottom.equalTo(-(view.safeAreaInsets.bottom + 50))
            } else {
                make.bottom.equalTo(-50)
                // Fallback on earlier versions
            }
            make.height.equalTo(30.0)
        }
        
        saveButton.addTarget(self, action: #selector(saveButtonAction), for: UIControlEvents.touchUpInside)
        
        if dataSource[0].items.isEmpty {
            getData {
                //
            }
        }
        
        questionView.dataSource = dataSource
        questionView.tableView.reloadData()
        let m = dataSource[3].items.last!
        _ = m.selectVariable.asObservable().subscribe(onNext: { [weak self] (result) in
            if let m = self?.dataSource[4] {
                m.viewHeight = CGFloat(result ? (70 + m.items.count * 30) : 0)
            }
            self?.questionView.tableView.reloadData()
        }, onError: nil, onCompleted: nil, onDisposed: nil)
    }
    
    @objc func saveButtonAction() {
        
        for (index, model) in dataSource.enumerated() {
            if !model.items.isEmpty {
                if model.selectedIndex.count == 0 || (model.selectedIndex.count == 1 && model.selectedIndex.first! == IndexNone) {
                    if index == 4{
                        let m = dataSource[3]
                        if m.selectedIndex == [0] {
                            break
                        }
                    }
                    makeToast("请填写或选择-\(model.questionTitle)")
                    return
                }
            }
        }
        
        let path = CDArchiverPath.liveStateFilePath
        let json = dataSource.toJSON()
        
        let dict = NSMutableDictionary()
        dict.setValue(json, forKey: "live")
        let success = dict.write(toFile: path, atomically: false)
        
        if success {
            makeToast("保存成功")
            navigationController?.popViewController(animated: true)
        } else {
            makeToast("保存失败")
        }
    }

    
    var question1Get = Variable(false)
    var question2Get = Variable(false)
    var question3Get = Variable(false)
    var question5Get = Variable(false)
    
    func getData( finish: @escaping () -> Void) {
        
        CDUtility.showHud()
        
        _ = Observable.combineLatest(question1Get.asObservable(), question2Get.asObservable(), question3Get.asObservable(), question5Get.asObservable()){ b0,b1,b2,b3 in
            return b0 && b1 && b2 && b3
        }.subscribe(onNext: { (finished) in
            if finished {
                CDUtility.hidHud()
                finish()
            }
        }, onError: nil, onCompleted: nil, onDisposed: nil)
        
        
        // 居住
        let liveJson = ["DictNo": "15"].convertToJsonString()
        let liveParamString = "<json>"+liveJson+"</json>"
        NetworkingHandle.fetchNetworkData(method: "getDictInfo", paramString: liveParamString, success: {[weak self] (dict) in
            if let strongSelf = self,let dataString = dict["DictDetail"] as? String {
                if let array = Mapper<ApplyChooseModel>().mapArray(JSONString: dataString) {
//                    strongSelf.dataSource[0].items = array
                    let dataArray = array.compactMap({ (model) -> QuestionItemModel? in
                        let model = QuestionItemModel(applyInfo: model)
                        model.uploadInfo = "JZZK"
                        return model
                    })
                    let model = strongSelf.dataSource[0]
                    model.items = dataArray
                    model.viewHeight = CGFloat(30 + 30 * model.items.count + 10)
                    strongSelf.dataSource[0] = model
                    strongSelf.question1Get.value = true
                    
                    strongSelf.questionView.tableView.reloadData()
                }
            }
        }) {
            print("")
        }
        
        // 经济
        let moneyJson = ["DictNo": "16"].convertToJsonString()
        let moneyParamString = "<json>"+moneyJson+"</json>"
        NetworkingHandle.fetchNetworkData(method: "getDictInfo", paramString: moneyParamString, success: {[weak self] (dict) in
            if let strongSelf = self,let dataString = dict["DictDetail"] as? String {
                if let array = Mapper<ApplyChooseModel>().mapArray(JSONString: dataString) {
                    //                    strongSelf.dataSource[0].items = array
                    let dataArray = array.compactMap({ (model) -> QuestionItemModel? in
                        let model = QuestionItemModel(applyInfo: model)
                        model.uploadInfo = "JJZK"
                        return model
                    })
                    let model = strongSelf.dataSource[1]
                    model.items = dataArray
                    model.viewHeight = CGFloat(30 + 30 * model.items.count + 10)
                    strongSelf.dataSource[1] = model
                    strongSelf.question2Get.value = true
                    
                    strongSelf.questionView.tableView.reloadData()
                }
            }
        }) {
            print("")
        }
        
        // 家庭支持
        let supportJson = ["DictNo": "17"].convertToJsonString()
        let supportParamString = "<json>"+supportJson+"</json>"
        NetworkingHandle.fetchNetworkData(method: "getDictInfo", paramString: supportParamString, success: {[weak self] (dict) in
            if let strongSelf = self,let dataString = dict["DictDetail"] as? String {
                if let array = Mapper<ApplyChooseModel>().mapArray(JSONString: dataString) {
                    //                    strongSelf.dataSource[0].items = array
                    let dataArray = array.compactMap({ (model) -> QuestionItemModel? in
                        let model = QuestionItemModel(applyInfo: model)
                        model.uploadInfo = "ZFZK"
                        return model
                    })
                    let model = strongSelf.dataSource[2]
                    model.items = dataArray
                    model.viewHeight = CGFloat(30 + 30 * model.items.count + 10)
                    strongSelf.dataSource[2] = model
                    strongSelf.question3Get.value = true
                    
                    strongSelf.questionView.tableView.reloadData()
                }
            }
        }) {
            print("")
        }
        
        // 照料
        let careJson = ["DictNo": "18"].convertToJsonString()
        let careParamString = "<json>"+careJson+"</json>"
        NetworkingHandle.fetchNetworkData(method: "getDictInfo", paramString: careParamString, success: {[weak self] (dict) in
            if let strongSelf = self,let dataString = dict["DictDetail"] as? String {
                if let array = Mapper<ApplyChooseModel>().mapArray(JSONString: dataString) {
                    //                    strongSelf.dataSource[0].items = array
                    let dataArray = array.compactMap({ (model) -> QuestionItemModel? in
                        let model = QuestionItemModel(applyInfo: model)
                        model.uploadInfo = "ZLRY"
                        return model
                    })
                    let model = strongSelf.dataSource[4]
                    model.items = dataArray
                    
                    let m = strongSelf.dataSource[3].items.last!
                    if m.selected {
                        model.viewHeight = CGFloat(30 + 30 * model.items.count + 40)
                    } else {
                        model.viewHeight = 0
                    }
                    strongSelf.dataSource[4] = model
                    strongSelf.question5Get.value = true
                    
                    strongSelf.questionView.tableView.reloadData()
                }
            }
        }) {
            print("")
        }
 
    }

}
